<template>
	<view class="container">
		<!-- 下拉刷新和上拉加载 -->
		<scroll-view
			scroll-y="true"
			class="scroll-container"
			:refresher-triggered="isRefreshing"
			:refresher-threshold="45" 
			@scrolltolower="onLoadMore"
		>
			<!-- 轮播图区域 -->
			<view class="hero-section">
				<swiper
					class="hero-swiper"
					:indicator-dots="true"
					:autoplay="true"
					:interval="3000"
					:duration="500"
					indicator-color="rgba(255,255,255,0.5)"
					indicator-active-color="#fff"
					@change="onSwiperChange"
				>
					<swiper-item v-for="(bannerItem, index) in shopInfo.banner_list" :key="index">
						<image class="hero-image" :src="globalConfig.site_url + bannerItem.image" mode="aspectFill" @tap="previewBannerImages(index)" />
					</swiper-item>
				</swiper>

				<!-- 返回按钮 -->
				<view class="back-btn" @click="goBack">
					<text class="back-icon">←</text>
				</view>

				<!-- 图片指示器 -->
				<view class="image-indicator" v-if="shopInfo.banner_list && shopInfo.banner_list.length > 1">
					<text class="indicator-text">{{ currentImageIndex + 1 }}/{{ shopInfo.banner_list.length }}</text>
				</view>
			</view>

			<!-- 店铺信息 -->
			<view class="store-info">
				<view class="store-header">
					<view class="store-title-section">
						<text class="store-name">{{ (shopInfo.agent_config && shopInfo.agent_config.title) || '店铺名称' }}</text>
						<view class="store-rating" v-if="shopInfo.rating">
							<text class="rating-score">{{ shopInfo.rating || '4.8' }}</text>
							<text class="rating-stars">⭐⭐⭐⭐⭐</text>
						</view>
					</view>
					<view class="guide-btn" @click="showGuide" v-if="shopInfo.agent_config && shopInfo.agent_config.guide">
						<text class="guide-icon">▷</text>
						<text class="guide-text">到店指南</text>
					</view>
				</view>

				<view class="store-details">
					<view class="address-row">
						<view class="status-dot" v-if="shopInfo.agent_config && shopInfo.agent_config.shop_status == 1"></view>
						<view class="status-dot status-ccc" v-if="shopInfo.agent_config && shopInfo.agent_config.shop_status == 2"></view>
						<view class="status-dot status-yellow" v-if="shopInfo.agent_config && shopInfo.agent_config.shop_status == 3"></view>
						<view class="status-dot status-red" v-if="shopInfo.agent_config && shopInfo.agent_config.shop_status == 4"></view>
						<!-- 店铺状态1=营业中,2=试营业,3=筹备中,4=已打烊 -->
						<text class="address">
							<template v-if="shopInfo.agent_config && shopInfo.agent_config.shop_status == 1">营业中-</template>
							<template v-if="shopInfo.agent_config && shopInfo.agent_config.shop_status == 2">试营业-</template>
							<template v-if="shopInfo.agent_config && shopInfo.agent_config.shop_status == 3">筹备中-</template>
							<template v-if="shopInfo.agent_config && shopInfo.agent_config.shop_status == 4">已打烊-</template>
							{{ getFullAddress() }}
						</text>
					</view>

					<view class="action-buttons">
						<view class="action-btn" @click="toggleFavorite()">
							<text class="action-icon" :style="{ color: shopInfo.collect == 1 ? '#ff4757' : '#1976d2' }">
								{{ shopInfo.collect == 1 ? '❤️' : '⭐' }}
							</text>
							<text class="action-text">{{ shopInfo.collect == 1 ? '已收藏' : '收藏' }}</text>
						</view>
						<view class="action-btn" @click="openNavigation">
							<text class="action-icon">📍</text>
							<text class="action-text">导航</text>
						</view>
						<view class="action-btn" @click="callStore">
							<text class="action-icon">📞</text>
							<text class="action-text">电话</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 功能菜单 -->
			<view class="menu-grid">
				<view class="menu-item" v-for="(menu, index) in menuItems" :key="index" @click="handleMenuClick(menu)">
					<view class="menu-icon-wrapper">
						<text class="menu-icon">{{ menu.icon }}</text>
					</view>
					<text class="menu-text">{{ menu.name }}</text>
				</view>
			</view>

			<!-- 分类选择 -->
			<view class="game-selection">
				<view class="game-card" v-for="(game, index) in shopInfo.type_list" :key="index" :class="{ active: type_id == game.id }" @click="switchGameType(game.id)">
					<view class="game-image-wrapper">
						<image class="game-image" :src="globalConfig.site_url + game.image" mode="aspectFit"></image>
					</view>
					<text class="game-name">{{ game.name }}</text>
				</view>
			</view>

			<!-- 房间列表 - 恢复原始逻辑和样式 -->
			<view class="room-list">
				<view class="room-card" v-for="(room, index) in roomList" :key="index">
					<!-- 房间标题 -->
					<view class="room-title">
						<!-- <image src="/static/brand-logo.png" class="brand-logo"></image> -->
						<text class="room-name">{{ room.name }}</text>
					</view>

					<!-- 房间信息 -->
					<view class="room-content">
						<view class="room-avatar" @click="previewRoomImages(room)">
							<view class="avatar-container">
								<view class="avatar-circle">
									<image class="panda-icon" :src="room.images[0]" alt=""></image>
								</view>
								<!-- <view class="speech-bubble">
									<text class="bubble-text">Hi-我是</text>
								</view> -->
								<view class="image-count">
									<text class="camera-icon">📷</text>
									<text class="count">{{ room.images ? room.images.length : 0 }}</text>
								</view>
							</view>
						</view>

						<view class="room-details">
							<!-- 设施标签 -->
							<view class="amenities">
								<view class="amenity-tag" v-for="(amenity, tagIndex) in room.tag" :key="tagIndex">
									<text class="amenity-text">{{ amenity }}</text>
								</view>
							</view>

							<!-- 价格和操作 -->
							<view class="price-section" @click="togglePackages(room)">
								<text class="price">{{ room.min_money }}元起</text>
								<view class="collapse-btn">
									<text class="collapse-text">{{ room.showPackages ? '收起' : '查看套餐' }}</text>
									<text class="arrow">{{ room.showPackages ? '▲' : '▼' }}</text>
								</view>
							</view>
						</view>
					</view>

					<!-- 套餐列表 -->
					<view class="packages-section" v-show="room.showPackages">
						<view class="package-item" v-for="(pkg, pkgIndex) in room.package_list" :key="pkgIndex">
							<text class="package-name">{{ pkg.name }}</text>
							<text class="package-price">{{ pkg.money }}</text>
						</view>
					</view>

					<!-- 时间选择和预订 - 应用新的时间可视化样式 -->
					<view class="booking-section">
						<!-- 时间段可视化 -->
						<view class="time-slots-section">
							<view class="slots-container">
								<view class="slots-row">
									<view
										v-for="(slot, slotIndex) in room.hours"
										:key="slotIndex"
										class="slot-item"
										:class="{
											'slot-unavailable': slot.selected == 1,
											'slot-available': slot.selected == 0
										}"
									></view>
								</view>
							</view>

							<view class="slots-container" style="margin-bottom: 20rpx; font-size: 20rpx">
								<view class="slots-row">
									<view v-for="(slot, slotIndex) in room.hours" :key="slotIndex" class="slot-item">{{ slot.hours }}</view>
								</view>
							</view>

							<view class="legend">
								<view class="legend-item">
									<view class="legend-color legend-unavailable"></view>
									<text class="legend-text">已预定时段</text>
								</view>
								<view class="legend-item">
									<view class="legend-color legend-available"></view>
									<text class="legend-text">可预定时段</text>
								</view>
							</view>
						</view>

						<!-- 套餐底部操作 -->
						<view class="package-actions" @click="goToBooking(room)">
							<view class="status-indicator">
								<view class="status-indicator-dot" v-if="room.status == 1">空闲中</view>
								<view class="status-indicator-dot" v-if="room.status == 2">进行中</view>
								<view class="status-indicator-dot" v-if="room.status == 3">待清洁</view>
								<view class="status-indicator-dot" v-if="room.status == 4">禁止使用</view>
							</view>
							<view class="book-btn">立即预定</view>
						</view>
					</view>
				</view>

				<!-- 加载更多提示 -->
				<view class="loading-more" v-if="isLoadingMore">
					<view class="loading-spinner"></view>
					<text class="loading-text">加载更多...</text>
				</view>

				<view class="no-more" v-if="noMore">
					<text class="no-more-text">— 没有更多数据了 —</text>
				</view>
			</view>
		</scroll-view>

		<!-- 图片弹出展示 -->
		<u-popup v-model="showImagePopupVisible" mode="center" border-radius="16" :mask-close-able="true" @close="closeImagePopup">
			<view class="image-popup">
				<view class="popup-header">
					<text class="popup-title">{{ popupTitle }}</text>
					<view class="popup-close" @click="closeImagePopup">
						<u-icon name="close" color="#999" size="20"></u-icon>
					</view>
				</view>
				<view class="popup-content">
					<image :src="popupImageUrl" mode="widthFix" class="popup-image" @click="handlePopupImageClick" />
				</view>
			</view>
		</u-popup>

		<!-- 充值弹出展示 -->
		<u-popup v-model="showRechargePopupVisible" mode="center" border-radius="16" :mask-close-able="true" @close="closeRechargePopup">
			<view class="recharge-popup">
				<view class="popup-header">
					<text class="popup-title">充值优惠</text>
					<view class="popup-close" @click="closeRechargePopup">
						<u-icon name="close" color="#999" size="20"></u-icon>
					</view>
				</view>
				<view class="popup-content">
					<image :src="rechargePopupImageUrl" mode="widthFix" class="popup-image" @click="handleRechargePopupClick" />
				</view>
			</view>
		</u-popup>

		<!-- 底部导航 -->
		<!-- <view class="bottom-nav" v-if="shopInfo.bottom_image">
			<img :src="shopInfo.bottom_image" alt="">
		</view> -->

		<!-- 到店指南视频弹窗 -->
		<view class="video-modal" v-if="showVideoModal" @tap="closeVideoModal">
			<view class="video-content" @tap.stop>
				<view class="video-header">
					<text class="video-title">到店指南</text>
					<text class="close-btn" @tap="closeVideoModal">✕</text>
				</view>
				<video class="guide-video" :src="guideVideoUrl" controls autoplay @error="onVideoError" @ended="onVideoEnded"></video>
			</view>
		</view>

		<!-- uView登录弹窗 -->
		<u-popup v-model="showLoginPopup" mode="center" border-radius="16" width="600rpx" :mask-close-able="true" @close="closeLoginPopup">
			<view class="login-popup">
				<view class="popup-header">
					<view class="popup-title">登录</view>
					<view class="popup-close" @click="closeLoginPopup">
						<u-icon name="close" color="#999" size="20"></u-icon>
					</view>
				</view>

				<view class="login-methods">
					<u-button type="success" shape="round" :loading="wechatLoading" @click="handleWechatLogin" :custom-style="wechatBtnStyle">
						<u-icon name="weixin-fill" color="#fff" size="20" style="margin-right: 10rpx"></u-icon>
						{{ wechatLoading ? '登录中...' : '微信登录' }}
					</u-button>

					<!-- <u-button 
            type="primary" 
            shape="round" 
            plain
            @click="handlePhoneLogin"
            :custom-style="phoneBtnStyle"
          >
            <u-icon name="phone" color="#0066ff" size="20" style="margin-right: 10rpx;"></u-icon>
            手机号登录
          </u-button> -->
				</view>

				<view class="login-tips">
					<text class="tips-text">登录即表示同意</text>
					<text class="link-text" @click="showPrivacy('agreement')">《用户协议》</text>
					<text class="tips-text">和</text>
					<text class="link-text" @click="showPrivacy('policy')">《隐私政策》</text>
				</view>
			</view>
		</u-popup>

		<!-- 充值优惠图片 -->
		<view class="bottom-recharge" v-if="rechargeInfo && rechargeInfo.open_recharge == '1' && rechargeInfo.recharge_image">
			<image :src="globalConfig.site_url + rechargeInfo.recharge_image" mode="widthFix" class="recharge-image" @click="handleRechargeImageClick" />
		</view>
	</view>
</template>

<script>
import request from '@/common/request.js';
import { mapGetters, mapActions, mapState } from 'vuex';
import { checkLoginStatus, getUserInfo, wechatMiniLogin, fetchUserInfo, fetchUserBalance, fetchUserVouchers, logout } from '@/common/auth.js';

export default {
	data() {
		return {
			isLoggedIn: false,
			showLoginPopup: false,
			pageLoading: false,
			wechatLoading: false,
			// 按钮样式
			wechatBtnStyle: {
				backgroundColor: '#07c160',
				borderColor: '#07c160',
				marginBottom: '20rpx'
			},
			shopId: '',
			type_id: '',
			shopInfo: {
				agent_config: {}
			},
			roomList: [],
			currentImageIndex: 0,
			page: 1,
			time: '',
			statusBarHeight: 0,
			scrollHeight: 0,
			isRefreshing: false,
			isLoadingMore: false,
			isFavorite: false,
			noMore: false,
			showVideoModal: false,
			guideVideoUrl: '',
			menuItems: [
				{ icon: '🎫', name: '优惠券' },
				{ icon: '⏰', name: '缓时' },
				{ icon: '💰', name: '团购验券' },
				{ icon: '🎫', name: '我的卡券' }
			],
			couponList: [],
			rechargeInfo: {},
			couponInfo: {},
			showImagePopupVisible: false,
			popupTitle: '',
			popupImageUrl: '',
			showRechargePopupVisible: false,
			rechargePopupImageUrl: ''
		};
	},

	computed: {
		// 使用mapGetters获取全局状态
		...mapGetters(['getConfig', 'getGaodeKey', 'getSiteName', 'getLocation']),

		// 使用mapState直接访问state
		...mapState({
			globalConfig: (state) => state.config,
			userLocation: (state) => state.location,
			userInfo: (state) => state.userInfo
		}),
		// 计算是否需要显示底部图片
		showBottomBanner() {
			const showCoupon = this.couponInfo && this.couponInfo.open_coupon == '1' && this.couponInfo.coupon_image;
			const showRecharge = this.rechargeInfo && this.rechargeInfo.open_recharge == '1' && this.rechargeInfo.recharge_image;
			return showCoupon || showRecharge;
		}
	},

	onLoad(options) {
		this.shopId = options.id || '';
		console.log(this.globalConfig.site_url, 'globalConfig.site_url');

		// 获取状态栏高度
		const systemInfo = uni.getSystemInfoSync();
		this.statusBarHeight = systemInfo.statusBarHeight || 0;

		// 计算滚动区域高度
		const windowHeight = systemInfo.windowHeight;
		const navHeight = 44;
		const bottomNavHeight = 60;
		this.scrollHeight = windowHeight - this.statusBarHeight - navHeight - bottomNavHeight;

		this.getshopInfo();

		// 获取今日日期
		this.today = this.formatDate(new Date());
	},

	methods: {
		// 检查登录状态
		async checkLoginStatus(room) {
			try {
				const isLoggedIn = await checkLoginStatus();
				this.isLoggedIn = isLoggedIn;

				if (isLoggedIn) {
					uni.navigateTo({
						url: `/pages/shop/shop-reservation?roomId=${room.id}&roomName=${encodeURIComponent(room.name)}&shopId=${this.shopId}`
					});
				} else {
					this.handleLogin();
				}
			} catch (error) {
				console.error('检查登录状态失败:', error);
				this.isLoggedIn = false;
			}
		},
		// 处理登录
		handleLogin() {
			if (!this.isLoggedIn) {
				this.showLoginPopup = true;
			}
		},
		// 关闭登录弹窗
		closeLoginPopup() {
			this.showLoginPopup = false;
			this.wechatLoading = false;
		},

		// 微信登录
		async handleWechatLogin() {
			if (this.wechatLoading) return;

			try {
				this.wechatLoading = true;

				// 调用微信小程序登录 - 确保函数名正确
				const result = await wechatMiniLogin(); // 这里调用wechatMiniLogin

				if (result.success) {
					this.isLoggedIn = true;
					this.userInfo = result.userInfo;
					await this.loadOrderData();
					this.getCategoryData();

					this.closeLoginPopup();
					this.$u.toast('登录成功');
				} else {
					throw new Error(result.message || '登录失败');
				}
			} catch (error) {
				console.error('微信登录失败:', error);
				this.$u.toast(error.message || '登录失败');
			} finally {
				this.wechatLoading = false;
			}
		},
		formatDate(date) {
			const year = date.getFullYear();
			const month = date.getMonth() + 1;
			const day = date.getDate();
			return `${year}-${month}-${day}`;
		},

		// 获取完整地址
		getFullAddress() {
			if (!this.shopInfo.agent_config) return '地址信息加载中...';

			const address = this.shopInfo.agent_config.address || '';
			const addressInfo = this.shopInfo.agent_config.address_info || '';
			return address + addressInfo;
		},

		// 获取商家信息数据
		getshopInfo() {
			let opts = {
				url: '/api/shop/shopInfo?id=' + this.shopId,
				method: 'get'
			};

			uni.showLoading({
				title: '加载中'
			});

			request
				.httpTokenRequest(opts)
				.then((res) => {
					uni.hideLoading();
					console.log('shopInfo response:', res);

					if (res && res.data && res.data.data) {
						this.shopInfo = res.data.data;
						this.couponList = res.data.data.coupon_list;
						this.rechargeInfo = res.data.data.recharge;
						this.couponInfo = res.data.data.coupon;

						// 确保 agent_config 存在
						if (!this.shopInfo.agent_config) {
							this.shopInfo.agent_config = {};
						}

						// 设置默认 type_id
						if (this.shopInfo.type_list && this.shopInfo.type_list.length > 0) {
							this.type_id = this.shopInfo.type_list[0].id;
						}

						console.log('店铺信息:', this.shopInfo);
						console.log('坐标信息:', {
							lat: this.shopInfo.agent_config.lat,
							lng: this.shopInfo.agent_config.lng,
							long: this.shopInfo.agent_config.long
						});

						// 检查并显示优惠券图片
						this.checkAndShowCouponImage();

						this.getRoomList();
					} else {
						uni.showToast({
							title: '获取店铺信息失败',
							icon: 'none'
						});
					}
				})
				.catch((error) => {
					uni.hideLoading();
					console.error('获取店铺信息失败:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				});
		},

		// 检查并显示优惠券图片
		checkAndShowCouponImage() {
			// 优先弹出优惠券
			if (this.couponInfo && this.couponInfo.open_coupon == '1' && this.couponInfo.coupon_image) {
				this.showImagePopup('优惠券', this.globalConfig.site_url + this.couponInfo.coupon_image);
			} else if (this.rechargeInfo && this.rechargeInfo.open_recharge == '1' && this.rechargeInfo.recharge_image) {
				// 只在没有优惠券时才直接弹充值
				// this.showRechargePopup(this.globalConfig.site_url + this.rechargeInfo.recharge_image);
			}
		},

		// 获取房间列表 - 恢复原始逻辑
		getRoomList() {
			let opts = {
				url: `/api/shop/getRoomList?id=${this.shopId}&type_id=${this.type_id}&page=${this.page}&time=${this.time}`,
				method: 'get'
			};

			request
				.httpRequest(opts)
				.then((res) => {
					console.log('getRoomList response:', res);

					if (res && res.data && res.data.data) {
						const newRoomList = res.data.data.list || [];

						// 判断返回的数据长度是否满足10条
						if (newRoomList.length < 10) {
							console.log('返回数据不足10条，设置noMore为true');
							this.noMore = true;
						}

						// 如果是第一页，直接替换；否则追加
						if (this.page === 1) {
							this.roomList = newRoomList;
						} else {
							this.roomList = [...this.roomList, ...newRoomList];
						}

						this.total = res.data.data.total;
						this.page = res.data.data.current_page;
						this.totalPage = res.data.data.total_page;

						// 修复图片URL处理逻辑
						this.roomList.forEach((item) => {
							if (item.images && item.images.length > 0) {
								item.images = item.images.map((img) => {
									return img.startsWith('http') ? img : this.globalConfig.site_url + img;
								});
							}
						});

						// 初始化房间显示状态 - 套餐默认展开
						this.roomList.forEach((item) => {
							item.showPackages = true;
						});

						console.log('房间列表:', this.roomList);
					}
				})
				.catch((error) => {
					console.error('获取房间列表失败:', error);
					uni.showToast({
						title: '获取房间列表失败',
						icon: 'none'
					});
				});
		},

		// 预览轮播图
		previewBannerImages(currentIndex) {
			if (!this.shopInfo.banner_list || this.shopInfo.banner_list.length === 0) {
				return;
			}

			const imageUrls = this.shopInfo.banner_list.map((item) => this.globalConfig.site_url + item.image);

			uni.previewImage({
				urls: imageUrls,
				current: imageUrls[currentIndex],
				success: () => {
					console.log('预览轮播图成功');
				},
				fail: (err) => {
					console.error('预览轮播图失败:', err);
				}
			});
		},

		// 预览房间图片
		previewRoomImages(room) {
			if (!room.images || room.images.length === 0) {
				uni.showToast({
					title: '暂无图片',
					icon: 'none'
				});
				return;
			}

			// 确保图片URL是完整的
			const imageUrls = room.images.map((img) => {
				return img.startsWith('http') ? img : this.globalConfig.site_url + img;
			});

			uni.previewImage({
				urls: imageUrls,
				current: imageUrls[0],
				success: () => {
					console.log('预览房间图片成功');
				},
				fail: (err) => {
					console.error('预览房间图片失败:', err);
					uni.showToast({
						title: '图片加载失败',
						icon: 'none'
					});
				}
			});
		},

		// 显示到店指南
		showGuide() {
			if (this.shopInfo.agent_config && this.shopInfo.agent_config.guide) {
				// 检查是否是视频URL
				const guideUrl = this.shopInfo.agent_config.guide;

				if (this.isVideoUrl(guideUrl)) {
					this.guideVideoUrl = guideUrl.startsWith('http') ? guideUrl : this.globalConfig.site_url + guideUrl;
					this.showVideoModal = true;
				} else {
					// 如果不是视频，显示文本或图片指南
					uni.showModal({
						title: '到店指南',
						content: guideUrl,
						showCancel: false,
						confirmText: '知道了'
					});
				}
			} else {
				uni.showToast({
					title: '该商家暂无到店指南',
					icon: 'none'
				});
			}
		},

		// 判断是否是视频URL
		isVideoUrl(url) {
			const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.m4v'];
			return videoExtensions.some((ext) => url.toLowerCase().includes(ext));
		},

		// 关闭视频弹窗
		closeVideoModal() {
			this.showVideoModal = false;
			this.guideVideoUrl = '';
		},

		// 视频播放错误
		onVideoError(e) {
			console.error('视频播放错误:', e);
			uni.showToast({
				title: '视频播放失败',
				icon: 'none'
			});
			this.closeVideoModal();
		},

		// 视频播放结束
		onVideoEnded() {
			console.log('视频播放结束');
		},

		// 导航功能 - 修复后的版本
		openNavigation() {
			console.log('点击导航按钮');
			console.log('店铺信息:', this.shopInfo);

			// 检查店铺信息是否存在
			if (!this.shopInfo || !this.shopInfo.agent_config) {
				uni.showToast({
					title: '店铺信息未加载完成，请稍后重试',
					icon: 'none'
				});
				return;
			}

			const config = this.shopInfo.agent_config;
			console.log('配置信息:', config);

			// 获取坐标信息 - 兼容不同的字段名
			let latitude = config.lat || config.latitude;
			let longitude = config.lng || config.long || config.longitude;

			console.log('坐标信息:', { latitude, longitude });

			// 检查坐标是否存在
			if (!latitude || !longitude) {
				uni.showToast({
					title: '店铺位置信息不完整，无法导航',
					icon: 'none'
				});
				return;
			}

			// 转换为数字类型
			latitude = parseFloat(latitude);
			longitude = parseFloat(longitude);

			// 验证坐标有效性
			if (isNaN(latitude) || isNaN(longitude)) {
				uni.showToast({
					title: '店铺坐标格式错误',
					icon: 'none'
				});
				return;
			}

			// 验证坐标范围（中国境内大致范围）
			if (latitude < 3.86 || latitude > 53.55 || longitude < 73.66 || longitude > 135.05) {
				uni.showToast({
					title: '店铺坐标超出有效范围',
					icon: 'none'
				});
				return;
			}

			const locationData = {
				latitude: latitude,
				longitude: longitude,
				name: config.title || '店铺',
				address: this.getFullAddress(),
				scale: 18
			};

			console.log('准备打开地图:', locationData);

			uni.openLocation({
				...locationData,
				success: () => {
					console.log('打开地图成功');
				},
				fail: (error) => {
					console.error('打开地图失败:', error);
					uni.showToast({
						title: '打开地图失败: ' + (error.errMsg || '未知错误'),
						icon: 'none'
					});
				}
			});
		},

		// 加载更多
		onLoadMore() {
			if (this.isLoadingMore || this.noMore) return;

			// 判断当前列表长度是否满足10条，不满足就不让翻页
			if (this.roomList.length < 10) {
				console.log('当前列表长度不足10条，不允许翻页');
				this.noMore = true;
				return;
			}

			this.isLoadingMore = true;
			this.page++;
			this.getRoomList();
			this.isLoadingMore = false;
		},

		// 下拉刷新
		async onRefresh() {
			console.log('触发下拉刷新');
			this.isRefreshing = true;

			try {
				// 重置页码
				this.page = 1;
				this.noMore = false;

				// 重新获取店铺信息和房间列表
				await Promise.all([this.getshopInfo(), this.getRoomList()]);

				this.$u.toast('刷新成功');
			} catch (error) {
				console.error('下拉刷新失败:', error);
				this.$u.toast('刷新失败');
			} finally {
				// 延迟重置刷新状态，确保动画完成
				setTimeout(() => {
					this.isRefreshing = false;
				}, 500);
			}
		},

		// 切换收藏状态
		async toggleFavorite() {
			const isLoggedIn = await checkLoginStatus();
			if (!isLoggedIn) {
				this.showLoginPopup = true;
				return;
			}

			// Determine which action to take
			const isCurrentlyCollected = this.shopInfo.collect == 1;

			if (isCurrentlyCollected) {
				// --- CANCEL FAVORITE ---
				try {
					const res = await request.httpTokenRequest({
						url: '/api/user/delCollect?agent_id=' + this.shopId, // Endpoint for cancelling
						method: 'get', // Typically POST for actions
						data: {
							shop_id: this.shopId // Assuming shop_id is the agent_id
						}
					});
					if (res.data.code === 1) {
						this.shopInfo.collect = 0; // Update UI
						this.$u.toast('已取消收藏');
					} else {
						this.$u.toast(res.data.msg || '操作失败');
					}
				} catch (error) {
					this.$u.toast('网络请求失败');
					console.error('取消收藏失败', error);
				}
			} else {
				// --- ADD FAVORITE ---
				try {
					const res = await request.httpTokenRequest({
						url: '/api/user/saveCollect?agent_id=' + this.shopId, // Endpoint for adding
						method: 'GET',
						data: {
							agent_id: this.shopId
						}
					});
					if (res.data.code === 1) {
						this.shopInfo.collect = 1; // Update UI
						this.$u.toast('收藏成功');
					} else {
						this.$u.toast(res.data.msg || '收藏失败');
					}
				} catch (error) {
					this.$u.toast('网络请求失败');
					console.error('收藏失败', error);
				}
			}
		},

		// 拨打电话
		callStore() {
			if (!this.shopInfo.agent_config || !this.shopInfo.agent_config.shop_phone) {
				uni.showToast({
					title: '店铺电话不存在',
					icon: 'none'
				});
				return;
			}

			uni.makePhoneCall({
				phoneNumber: this.shopInfo.agent_config.shop_phone,
				success: () => {
					console.log('拨打电话成功');
				},
				fail: (err) => {
					console.log('拨打电话失败', err);
					uni.showToast({
						title: '拨打电话失败',
						icon: 'none'
					});
				}
			});
		},

		// 菜单点击
		async handleMenuClick(menu) {
			let url = '';
			let needsLogin = false;

			switch (menu.name) {
				case '优惠券':
					url = `/pages/user/coupons?shopId=${this.shopId}`;
					break;
				case '缓时':
					url = '/pages/index/order';
					needsLogin = true;
					break;
				case '团购验券':
					url = '/pages/wallet/verify';
					needsLogin = true;
					break;
				case '我的卡券':
					url = `/pages/user/coupons?shopId=${this.shopId}`;
					break;
				default:
					this.$u.toast('功能开发中...');
					return;
			}

			if (needsLogin) {
				const isLoggedIn = await checkLoginStatus();
				if (!isLoggedIn) {
					this.showLoginPopup = true;
					// We don't navigate here, assuming login popup will handle it
					// or we can store the navigation and execute after login
					return;
				}
			}

			// 判断是否跳转订单页面
			if (url === '/pages/index/order' || url === '/pages/index/tabbar?page=order') {
				uni.reLaunch({
					url: '/pages/index/tabbar?page=order'
				});
				return;
			}

			uni.navigateTo({
				url: url
			});
		},

		// 切换游戏类型
		switchGameType(id) {
			this.type_id = id;
			this.page = 1;
			this.getRoomList();
		},

		// 切换套餐显示
		togglePackages(room) {
			room.showPackages = !room.showPackages;
			this.$forceUpdate();
		},

		// 去预订 - 恢复原始逻辑
		goToBooking(room) {
			this.checkLoginStatus(room);
			console.log('预订房间:', room);
		},

		// 返回
		goBack() {
			uni.navigateBack();
		},

		// 轮播图切换
		onSwiperChange(e) {
			this.currentImageIndex = e.detail.current;
		},

		// 新增：点击充值图片
		handleRechargeImageClick() {
			// 跳转到充值页面
			uni.navigateTo({
				url: '/pages/wallet/recharge'
			});
		},

		showPrivacy(type) {
			const urlKey = type === 'policy' ? 'yszc_url' : 'yhxy_url';
			const title = type === 'policy' ? '隐私政策' : '用户协议';
			if (this.globalConfig && this.globalConfig[urlKey]) {
				uni.navigateTo({
					url: `/pages/common/webview?url=${encodeURIComponent(this.globalConfig[urlKey])}&title=${encodeURIComponent(title)}`
				});
			} else {
				this.$u.toast('协议地址未配置');
			}
		},

		// 图片弹出展示
		showImagePopup(title, imageUrl) {
			this.popupTitle = title;
			this.popupImageUrl = imageUrl;
			this.showImagePopupVisible = true;
		},

		// 关闭图片弹出展示
		closeImagePopup() {
			this.showImagePopupVisible = false;
		},

		// 处理图片点击
		handlePopupImageClick() {
			// 根据当前显示的图片类型执行相应操作
			if (this.popupTitle === '优惠券') {
				this.closeImagePopup();
				this.handleCouponClick();
			} else if (this.popupTitle === '充值优惠') {
				this.closeImagePopup();
				this.handleRechargeClick();
			}
		},
		// 领取优惠券
		handleCouponClick() {
			let opts = {
				url: `/api/user/saveCoupon?id=${this.shopId}`,
				method: 'get'
			};

			request
				.httpTokenRequest(opts)
				.then((res) => {
					console.log('saveCoupon response:', res);

					if (res && res.data.code == 1) {
						console.log('领券:', this.res);
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						});
					}
				})
				.catch((error) => {
					console.error('领券失败:', error);
					uni.showToast({
						title: '领券失败',
						icon: 'none'
					});
				});
		},

		// 充值弹出展示
		showRechargePopup(imageUrl) {
			this.rechargePopupImageUrl = imageUrl;
			this.showRechargePopupVisible = true;
		},

		// 关闭充值弹出展示
		closeRechargePopup() {
			this.showRechargePopupVisible = false;
		},

		// 处理充值点击
		handleRechargePopupClick() {
			this.closeRechargePopup();
			this.handleRechargeClick();
		}
	}
};
</script>

<style lang="scss">
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 220rpx; /* 为底部充值图片留出空间 */
	position: relative;
}

.scroll-container {
	height: 100vh;
}

.hero-section {
	position: relative;
	height: 300px;
}

.hero-swiper {
	width: 100%;
	height: 100%;
}

.hero-image {
	width: 100%;
	height: 100%;
	cursor: pointer;
}

.back-btn {
	position: absolute;
	top: 50px;
	left: 20px;
	width: 40px;
	height: 40px;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	font-size: 18px;
	z-index: 10;
}

.image-indicator {
	position: absolute;
	bottom: 20px;
	right: 20px;
	background-color: rgba(0, 0, 0, 0.6);
	color: white;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	z-index: 10;
}

.indicator-text {
	font-size: 24rpx;
}

.store-info {
	background-color: white;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 0 0 20rpx 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.store-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 30rpx;
}

.store-title-section {
	flex: 1;
}

.store-name {
	font-size: 40rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 12rpx;
}

.store-rating {
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.rating-score {
	font-size: 28rpx;
	color: #ff6b35;
	font-weight: bold;
}

.rating-stars {
	font-size: 24rpx;
}

.guide-btn {
	display: flex;
	align-items: center;
	color: #1976d2;
	font-size: 28rpx;
	background: linear-gradient(135deg, #f0f8ff 0%, #e3f2fd 100%);
	border: 2rpx solid #1976d2;
	padding: 20rpx 32rpx;
	border-radius: 50rpx;
	box-shadow: 0 4rpx 8rpx rgba(25, 118, 210, 0.2);
}

.guide-icon {
	margin-right: 8rpx;
	font-size: 32rpx;
}

.store-details {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
}

.address-row {
	display: flex;
	align-items: flex-start;
	flex: 1;
}

.status-dot {
	width: 12rpx;
	height: 12rpx;
	background-color: #4caf50;
	border-radius: 50%;
	margin-right: 16rpx;
	margin-top: 8rpx;
	flex-shrink: 0;
}

.status-red {
	background-color: #ff4757;
}

.status-yellow {
	background-color: #ffc107;
}

.status-ccc {
	background-color: #ccc;
}

.address {
	color: #666;
	font-size: 28rpx;
	line-height: 1.5;
}

.action-buttons {
	display: flex;
	gap: 24rpx;
}

.action-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
	padding: 16rpx;
	border-radius: 16rpx;
	background-color: #f8f9fa;
	min-width: 80rpx;
}

.action-icon {
	font-size: 32rpx;
	color: #1976d2;
}

.action-text {
	font-size: 24rpx;
	color: #666;
}

.menu-grid {
	display: flex;
	background: white;
	margin: 0 20rpx 20rpx;
	border-radius: 20rpx;
	padding: 40rpx 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.menu-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 16rpx;
}

.menu-icon-wrapper {
	width: 80rpx;
	height: 80rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.menu-icon {
	font-size: 40rpx;
}

.menu-text {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.game-selection {
	display: flex;
	gap: 20rpx;
	margin: 0 20rpx 20rpx;
}

.game-card {
	flex: 1;
	background: white;
	border-radius: 20rpx;
	padding: 30rpx 20rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	transition: all 0.3s ease;
	border: 3rpx solid transparent;

	&.active {
		background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%);
		color: white;
		transform: translateY(-4rpx);
		box-shadow: 0 8rpx 20rpx rgba(25, 118, 210, 0.3);

		.game-name {
			color: white;
		}

		.game-image-wrapper {
			background: rgba(255, 255, 255, 0.2);
		}
	}
}

.game-image-wrapper {
	width: 80rpx;
	height: 80rpx;
	background: #f5f5f5;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 12rpx;
}

.game-image {
	width: 100%;
	height: 100%;
}

.game-name {
	font-size: 28rpx;
	font-weight: 500;
	color: #333;
}

/* 房间列表 - 恢复原始样式 */
.room-list {
	margin: 20rpx;
	padding-bottom: 200rpx;
}

.room-card {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.room-title {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
}

.brand-logo {
	width: 60rpx;
	height: 60rpx;
	margin-right: 20rpx;
}

.room-name {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.room-content {
	display: flex;
	margin-bottom: 30rpx;
}

.room-avatar {
	margin-right: 30rpx;
}

.avatar-container {
	position: relative;
	width: 200rpx;
	height: 200rpx;
}

.avatar-circle {
	width: 200rpx;
	height: 200rpx;
	// border-radius: 50%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	overflow: hidden;
}

.panda-icon {
	width: 100%;
	height: 100%;
	// border-radius: 50%;
}

.speech-bubble {
	position: absolute;
	top: -20rpx;
	right: 20rpx;
	background: #4caf50;
	color: white;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;

	&::after {
		content: '';
		position: absolute;
		bottom: -10rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 0;
		height: 0;
		border-left: 10rpx solid transparent;
		border-right: 10rpx solid transparent;
		border-top: 10rpx solid #4caf50;
	}
}

.image-count {
	position: absolute;
	bottom: 16rpx;
	right: 16rpx;
	background: rgba(0, 0, 0, 0.6);
	color: white;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.camera-icon,
.count {
	font-size: 24rpx;
}

.room-details {
	flex: 1;
}

.amenities {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
	margin-bottom: 30rpx;
}

.amenity-tag {
	background: #f0f0f0;
	padding: 12rpx 20rpx;
	border-radius: 20rpx;
}

.amenity-text {
	font-size: 24rpx;
	color: #666;
}

.price-section {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.price {
	font-size: 36rpx;
	color: #1976d2;
	font-weight: bold;
}

.collapse-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	color: #666;
	font-size: 28rpx;
}

.arrow {
	font-size: 24rpx;
}

.packages-section {
	border-top: 2rpx solid #f0f0f0;
	padding-top: 30rpx;
	margin-top: 30rpx;
}

.package-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 0;
	border-bottom: 2rpx solid #f8f8f8;

	&:last-of-type {
		border-bottom: none;
	}
}

.package-name {
	font-size: 32rpx;
	color: #1976d2;
	font-weight: 500;
}

.package-price {
	font-size: 32rpx;
	color: #f44336;
	font-weight: bold;
}

.booking-section {
	margin-top: 30rpx;
}

/* 新的时间段可视化样式 - 从附件中提取 */
.time-slots-section {
	background-color: #fff;
	padding: 30rpx;
	// margin-bottom: 20rpx;
	border-radius: 16rpx;
	border-top: 2rpx solid #f0f0f0;
}

.slots-container {
	/* margin-bottom: 30rpx; */
}

.slots-row {
	display: flex;
	flex-wrap: wrap;
}

.slot-item {
	width: 3.1%;
	height: 32rpx;
	border-radius: 4rpx;
	margin-right: 1%;
	margin-bottom: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 20rpx;
	color: #666;
}

.slot-unavailable {
	background-color: #007aff;
	color: white;
}

.slot-available {
	background-color: #d0d0d0;
	color: #666;
}

.legend {
	display: flex;
	flex-wrap: wrap;
	margin-top: 20rpx;
}

.legend-item {
	display: flex;
	align-items: center;
	margin-right: 30rpx;
	margin-bottom: 10rpx;
}

.legend-color {
	width: 24rpx;
	height: 24rpx;
	border-radius: 4rpx;
	margin-right: 8rpx;
}

.legend-unavailable {
	background-color: #007aff;
}

.legend-available {
	background-color: #d0d0d0;
}

.legend-text {
	font-size: 24rpx;
	color: #666;
}

.package-actions {
	display: flex;
	justify-content: space-between;
	align-items: center;
	// margin-top: 30rpx;
}

.status-indicator {
	background: #e0e0e0;
	padding: 16rpx 32rpx;
	border-radius: 40rpx;
}

.book-btn {
	background: #1976d2;
	color: white;
	padding: 20rpx 40rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.loading-more {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 16rpx;
	padding: 40rpx 0;
}

.loading-spinner {
	width: 32rpx;
	height: 32rpx;
	border: 3rpx solid #f3f3f3;
	border-top: 3rpx solid #1976d2;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}

.no-more {
	text-align: center;
	padding: 40rpx 0;
}

.no-more-text {
	font-size: 28rpx;
	color: #ccc;
	font-style: italic;
}

.bottom-nav {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 60rpx;
}

/* 视频弹窗样式 */
.video-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.8);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
}

.video-content {
	width: 90%;
	max-width: 600rpx;
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
}

.video-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.video-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.close-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f5f5f5;
	border-radius: 50%;
	font-size: 32rpx;
	color: #666;
}

.guide-video {
	width: 100%;
	height: 400rpx;
}

.login-popup {
	padding: 40rpx;

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;

		.popup-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.popup-close {
			padding: 10rpx;
		}
	}

	.login-methods {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-bottom: 40rpx;
	}

	.login-tips {
		text-align: center;
		font-size: 24rpx;
		color: #999;

		.tips-text {
			color: #999;
		}

		.link-text {
			color: #0066ff;
			text-decoration: underline;
		}
	}
}

.recharge-image-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 100;
	height: 120rpx;
	background-color: #f0f0f0;
}

.recharge-image {
	width: 100%;
	height: 100%;
	display: block;
}

.detail-page {
	padding-bottom: 140rpx; /* 为底部固定栏留出比其高度稍多的空间 */
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 60rpx;
}

.left-actions {
	display: flex;
	gap: 24rpx;
}

.right-actions {
	display: flex;
	gap: 24rpx;
}

/* 图片弹出样式 */
.image-popup {
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
	max-width: 90vw;
	max-height: 80vh;
}

.recharge-popup {
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
	max-width: 90vw;
	max-height: 80vh;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.popup-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.popup-close {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f5f5f5;
	border-radius: 50%;
	font-size: 32rpx;
	color: #666;
}

.popup-content {
	padding: 20rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.popup-image {
	max-width: 100%;
	max-height: 60vh;
	border-radius: 10rpx;
}

/* 充值优惠图片 */
.bottom-recharge {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 100;
	height: 200rpx;
	background-color: #f0f0f0;
}

.recharge-image {
	width: 100%;
	height: 100%;
	display: block;
}
</style>
